/**
 * 1.给window绑定键盘按下的事件
 * 2.获取按的键
 * 
 */


function genKeyToElement(){
    //空对象
    const keyToElement = {}
    //找到所有的div.key元素
    const keyEles = document.querySelectorAll('.key')
    //遍历每一个元素
    // keyEles.forEach(function(keyEle){
    //     const key = keyEle.dataset.key
    //     keyToElement[key] = keyEle
    // })
    for(let i=0;i<keyEles.length;i++){
        let keyEle = keyEles[i]
        let keyCode = keyEle.dataset.key
        keyToElement[keyCode] = keyEle
    }
    return keyToElement
}

const keyToElement = genKeyToElement()
/*
const keyToElement = {
    keyA:`<div class="key" data-key="KeyA">`,
    KeyS:`<div class="key" data-key="KeyS">`,
    KeyL:`<div class="key" data-key="KeyL">`
}
*/
 window.addEventListener('keydown',function(e){
    const key = e.code//keyA
    // const keyEle = keyToElement[key]
    const keyEle = document.querySelector(`.key[data-key=${key}]`)
    if(keyEle){
        keyEle.classList.add('playing')
        const audioEle = keyEle.firstElementChild
        audioEle.play()
    }
 })

 window.addEventListener('keyup',function(e){
    const key = e.code
    const keyEle = keyToElement[key]
    if(keyEle){
        keyEle.classList.remove('playing')
    }
 })

 